<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Search</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container mt-5">
    <h1>Document Search and Upload</h1>

    <!-- 上传文件表单 -->
    <form action="creatIndex" method="POST" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="file" class="form-label">Choose file</label>
            <input type="file" class="form-control" id="file" name="file" required>
        </div>
        <button type="submit" class="btn btn-primary">Upload and Index</button>
    </form>

    <hr>

    <!-- 搜索表单 -->
    <form action="/search" method="GET">
        <div class="mb-3">
            <label for="keyword" class="form-label">Search for Document</label>
            <input type="text" class="form-control" id="keyword" name="keyword" required>
        </div>
        <button type="submit" class="btn btn-success">Search</button>
    </form>

    <!-- 显示搜索结果 -->
    <div id="search-results" class="mt-4">
        <h3>Search Results</h3>
        <ul id="results-list"></ul>
    </div>
</div>

<script>
    // 表单提交后刷新页面，显示索引成功的消息
    const form = document.querySelector('form[action="creatIndex"]');
    form.addEventListener('submit', (event) => {
        event.preventDefault();
        const formData = new FormData(form);
        fetch('creatIndex', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            alert(data);  // 弹出成功提示
            form.reset(); // 清空表单
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

    // 搜索结果处理
    const searchForm = document.querySelector('form[action="/search"]');
    searchForm.addEventListener('submit', (event) => {
        event.preventDefault();
        const keyword = document.querySelector('#keyword').value;
        fetch(`/search?keyword=${keyword}`)
            .then(response => response.json())
            .then(data => {
                const resultsList = document.querySelector('#results-list');
                resultsList.innerHTML = '';  // 清空之前的搜索结果
                data.forEach(item => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `${item.fileName} - ${item.content}`;
                    resultsList.appendChild(listItem);
                });
            })
            .catch(error => {
                console.error('Error:', error);
            });
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
